import React, { useState, useEffect } from 'react';
import { useParams, useLocation, useNavigate } from 'react-router-dom';
import { ArrowLeft, MapPin, Phone, Globe, Building2, Star, Users } from 'lucide-react';
import request from '../api/request';

interface HospitalData {
  hospitalName: string;
  hospitalDescription: string;
}

interface HospitalDetail {
  id: string;
  name: string;
  level: string;
  city: string;
  address: string;
  state: string;
  admin: string;
  rating: string;
  views: string;
  phone?: string;
  description?: string;
  image?: string;
  // API返回的字段
  socoid?: string;
  nosocomium?: string;
  socolv?: string;
  sococity?: string;
  socostate?: string;
  socoadmin?: string;
  socoimage?: string;
}

export default function HospitalDetailPage() {
  const { id } = useParams<{ id: string }>();
  const location = useLocation();
  const navigate = useNavigate();
  const [hospital, setHospital] = useState<HospitalDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // 从路由状态获取医院信息
  const routeHospitalData = location.state as HospitalData;

  // 获取医院详情
  useEffect(() => {
    const fetchHospitalDetail = async () => {
      if (!id) {
        setError('医院ID不存在');
        setLoading(false);
        return;
      }

      try {
        console.log('开始获取医院详情，ID:', id);
        
        // 尝试从API获取医院详情
        const response = await request.get(`/nosocomium/detail`, {
          params: { id }
        });

        console.log('医院详情API响应:', response);

        if (response?.data?.data) {
          const data = response.data.data;
          console.log('医院详情原始数据:', data);
          
          // 使用正确的字段名映射
          const hospitalData = {
            id: String(data.socoid || data.id || id),
            name: data.nosocomium || data.name || data.hospitalname || routeHospitalData?.hospitalName || '未知医院',
            level: data.socolv || data.lv || data.level || '医院',
            city: data.sococity || data.city || '未知城市',
            address: data.address || data.location || '地址信息',
            state: data.socostate || data.state || data.type || '医院类型',
            admin: data.socoadmin || data.admin || data.department || '知名科室',
            rating: data.rating || '4.5',
            views: data.views || '0',
            phone: data.phone || data.contact,
            description: data.description || routeHospitalData?.hospitalDescription,
            image: data.socoimage || data.image || data.hospitalimage,
            // 保存原始API数据
            socoid: data.socoid,
            nosocomium: data.nosocomium,
            socolv: data.socolv,
            sococity: data.sococity,
            socostate: data.socostate,
            socoadmin: data.socoadmin,
            socoimage: data.socoimage,
          };
          
          console.log('处理后的医院数据:', hospitalData);
          setHospital(hospitalData);
        } else {
          console.log('API返回空数据，使用备选数据');
          // 如果没有API数据，使用路由状态中的信息
          setHospital({
            id: id,
            name: routeHospitalData?.hospitalName || '未知医院',
            level: '医院',
            city: '未知城市',
            address: '地址信息',
            state: '医院类型',
            admin: '知名科室',
            rating: '4.5',
            views: '0',
            description: routeHospitalData?.hospitalDescription,
          });
        }
      } catch (e) {
        console.warn('获取医院详情失败:', e);
        console.log('错误详情:', {
          message: e.message,
          status: e.response?.status,
          statusText: e.response?.statusText,
          url: e.config?.url,
          params: e.config?.params
        });
        
        // 使用路由状态中的信息作为备选
        setHospital({
          id: id,
                      name: routeHospitalData?.hospitalName || '未知医院',
          level: '医院',
          city: '未知城市',
          address: '地址信息',
          state: '医院类型',
          admin: '知名科室',
          rating: '4.5',
          views: '0',
                      description: routeHospitalData?.hospitalDescription,
        });
      } finally {
        setLoading(false);
      }
    };

    fetchHospitalDetail();
  }, [id, routeHospitalData]);

  const handleBack = () => {
    navigate(-1);
  };

  // 加载状态
  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50">
        <div className="p-4">
          <div className="w-6 h-6 border-2 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto"></div>
          <p className="text-center text-gray-500 mt-2">加载中...</p>
        </div>
      </div>
    );
  }

  // 错误状态
  if (error || !hospital) {
    return (
      <div className="min-h-screen bg-gray-50">
        <div className="p-4">
          <div className="text-center text-red-500">
            <p>{error || '医院信息不存在'}</p>
            <button 
              onClick={handleBack}
              className="mt-4 px-4 py-2 bg-primary-500 text-white rounded-lg"
            >
              返回
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 头部 */}
      <div className="bg-white border-b border-gray-200">
        <div className="px-4 py-3 flex items-center space-x-3">
          <button 
            onClick={handleBack}
            className="p-2 rounded-lg hover:bg-gray-100"
          >
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-lg font-semibold text-gray-900 truncate">
            {hospital.name}
          </h1>
        </div>
      </div>

      {/* 医院基本信息 */}
      <div className="bg-white mb-3">
        <div className="p-4">
          <div className="flex items-start space-x-4">
            {hospital.image && hospital.image.startsWith('http') ? (
              <img 
                src={hospital.image} 
                alt={hospital.name}
                className="w-20 h-20 rounded-lg object-cover"
              />
            ) : (
              <div className="w-20 h-20 rounded-lg bg-green-100 flex items-center justify-center">
                <Building2 size={32} className="text-green-600" />
              </div>
            )}
            <div className="flex-1">
              <h2 className="text-xl font-bold text-gray-900 mb-2">{hospital.name}</h2>
              <div className="flex items-center space-x-2 mb-2">
                <span className="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">
                  {hospital.level}
                </span>
                <span className="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded-full">
                  {hospital.state}
                </span>
              </div>
              <div className="flex items-center space-x-4 text-sm text-gray-600">
                <div className="flex items-center space-x-1">
                  <Star size={16} className="text-yellow-500" />
                  <span>{hospital.rating}</span>
                </div>
                <div className="flex items-center space-x-1">
                  <Users size={16} className="text-gray-400" />
                  <span>{hospital.views} 浏览</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 医院详细信息 */}
      <div className="bg-white mb-3">
        <div className="p-4 space-y-4">
          <div className="flex items-start space-x-3">
            <MapPin size={20} className="text-gray-400 mt-0.5" />
            <div className="flex-1">
              <h3 className="text-sm font-medium text-gray-900 mb-1">地址</h3>
              <p className="text-sm text-gray-600">{hospital.city} {hospital.address}</p>
            </div>
          </div>

          {hospital.phone && (
            <div className="flex items-start space-x-3">
              <Phone size={20} className="text-gray-400 mt-0.5" />
              <div className="flex-1">
                <h3 className="text-sm font-medium text-gray-900 mb-1">联系电话</h3>
                <p className="text-sm text-gray-600">{hospital.phone}</p>
              </div>
            </div>
          )}

          <div className="flex items-start space-x-3">
            <Globe size={20} className="text-gray-400 mt-0.5" />
            <div className="flex-1">
              <h3 className="text-sm font-medium text-gray-900 mb-1">知名科室</h3>
              <p className="text-sm text-gray-600">{hospital.admin}</p>
            </div>
          </div>

          {hospital.description && (
            <div className="pt-4 border-t border-gray-100">
              <h3 className="text-sm font-medium text-gray-900 mb-2">医院简介</h3>
              <p className="text-sm text-gray-600 leading-relaxed">
                {hospital.description}
              </p>
            </div>
          )}
        </div>
      </div>

      {/* 操作按钮 */}
      <div className="p-4 space-y-3">
        <button className="w-full py-3 bg-primary-500 text-white rounded-lg font-medium hover:bg-primary-600 transition-colors">
          预约挂号
        </button>
        <button className="w-full py-3 bg-white border border-primary-500 text-primary-500 rounded-lg font-medium hover:bg-primary-50 transition-colors">
          查看医生
        </button>
        <button className="w-full py-3 bg-white border border-gray-300 text-gray-700 rounded-lg font-medium hover:bg-gray-50 transition-colors">
          导航前往
        </button>
      </div>
    </div>
  );
} 